package com.iteaj.demo.server;

import com.iteaj.network.ProtocolType;
import com.iteaj.network.message.DeviceMessageHead;
import com.iteaj.network.message.UnParseBodyMessage;
import com.iteaj.network.utils.ByteUtil;

import java.io.IOException;
import java.net.ProtocolException;
import java.nio.charset.StandardCharsets;

public class ServerDemoMessage extends UnParseBodyMessage {

    public ServerDemoMessage(byte[] message) {
        super(message);
    }

    public ServerDemoMessage(MessageHead head, MessageBody body) {
        super(head, body);
    }

    @Override
    public UnParseBodyMessage build() throws IOException {
        final String messageHex = ByteUtil.bytesToHex(message);

        // 读取前面3个字节作为设备编号
        final String deviceSn = messageHex.substring(0, 6);

        final String type = messageHex.substring(6, 8);

        // 14字节的日期作为messageId
        final String messageId = messageHex.substring(8, 22);

        ProtocolType protocolType;
        if(type.equals(ServerProtocolType.PlatformRequest.getCode())) {
            protocolType = ServerProtocolType.PlatformRequest;
        } else if(type.equals(ServerProtocolType.ClientRequest.getCode())) {
            protocolType = ServerProtocolType.ClientRequest;
        } else {
            throw new ProtocolException("未知报文类型["+ messageHex +"]");
        }

        // 不需要报文体
        this.messageBody = VOID_MESSAGE_BODY;

        this.messageHead = new DeviceMessageHead(new byte[]{}, messageId, deviceSn, protocolType);

        this.setMessage(message);
        return this;
    }
}
